from api import models
from rest_framework import serializers


class CreateCommentSerializer(serializers.ModelSerializer):
    create_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = models.Comment
        fields = ['news', 'reply', 'content', 'depth', 'create_datetime']
        read_only_fields = ['depth', ]
        extra_kwargs = {
            'news': {'write_only': True}
        }


class ListCommentSerializer(serializers.ModelSerializer):
    create_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    children = serializers.SerializerMethodField()

    class Meta:
        model = models.Comment
        fields = ['create_datetime', "reply", "content", 'children']

    def get_children(self, obj):
        # 获取当前跟根评论的所有子评论
        descendant_queryset = models.Comment.objects.filter(root=obj).order_by('id')

        # 构建字典
        descendant_dict = {}
        for descendant in descendant_queryset:
            ser = CreateCommentSerializer(instance=descendant, many=False)
            row = {'children': []}
            row.update(ser.data)
            descendant_dict[descendant.id] = row

        children_list = []
        for cid, item in descendant_dict.items():
            depth = item['depth']
            if depth == 1:
                children_list.append(item)
                continue
            reply_id = item['reply']
            descendant_dict[reply_id]['children'].append(item)
        return children_list
